package com.njtoyo.taxi.admin.service.open.impl;

import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.DateUtil;
import com.baomidou.dynamic.datasource.annotation.DS;
import com.njtoyo.taxi.admin.library.Const;
import com.njtoyo.taxi.admin.logic.open.BigOrderNotificationLogic;
import com.njtoyo.taxi.admin.mapper.master.entity.CustomerLogoutLog;
import com.njtoyo.taxi.admin.mapper.master.entity.DriverAuditInfo;
import com.njtoyo.taxi.admin.mapper.master.entity.User;
import com.njtoyo.taxi.admin.mapper.master.enums.CustomerLogoutLogState;
import com.njtoyo.taxi.admin.mapper.master.mapper.CustomerLogoutLogMapper;
import com.njtoyo.taxi.admin.mapper.master.mapper.DriverAuditInfoMapper;
import com.njtoyo.taxi.admin.mapper.master.mapper.UserMapper;
import com.njtoyo.taxi.admin.rest.wrapper.open.notification.BigOrderWrapper;
import com.njtoyo.taxi.admin.rest.wrapper.open.notification.CustomerLogoutWrapper;
import com.njtoyo.taxi.admin.rest.wrapper.open.notification.DriverCertificateExpirationWrapper;
import com.njtoyo.taxi.admin.rest.wrapper.open.notification.DriverRegisterNotificationWrapper;
import com.njtoyo.taxi.admin.service.open.NotificationService;
import com.taxi.entity.common.RestResult;
import com.taxi.entity.common.ResultEnum;
import me.chanjar.weixin.common.error.WxErrorException;
import me.chanjar.weixin.cp.api.WxCpGroupRobotService;
import me.chanjar.weixin.cp.api.WxCpService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.Objects;

@Service
@DS(Const.PRIMARY_DS)
public class NotificationServiceImpl implements NotificationService {

    @Autowired
    private WxCpService wxCpService;

    @Value("${config.weixinRobot.customerLogout}")
    private String customerLogoutKey;

    @Value("${config.weixinRobot.orderAssistant}")
    private String orderAssistantKey;

    @Value("${config.weixinRobot.driverRegister}")
    private String driverRegisterKey;

    @Autowired
    private CustomerLogoutLogMapper customerLogoutLogMapper;

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private BigOrderNotificationLogic bigOrderNotificationLogic;

    @Autowired
    private DriverAuditInfoMapper driverAuditInfoMapper;

    @Override
    public RestResult customerLogout(CustomerLogoutWrapper wrapper) throws WxErrorException {
        Long id = wrapper.getId();
        CustomerLogoutLog log = customerLogoutLogMapper.selectById(id);
        if (Objects.isNull(log)) {
            return RestResult.build(ResultEnum.NOT_FOUND);
        }
        if (!log.getLogoutState().equals(CustomerLogoutLogState.processing)) {
            return RestResult.failed("此申请不处于审核中");
        }
        User user = userMapper.selectById(log.getCustomerId());
        if (Objects.isNull(user)) {
            return RestResult.failed("乘客不存在");
        }

        String content = String.format("手机号为 %s 的乘客申请注销，申请原因：%s。请及时处理。", user.getMobileNumber(), log.getLogoutReason());

        WxCpGroupRobotService groupRobotService = wxCpService.getGroupRobotService();
        groupRobotService.sendMarkdown(getWebhookUrlByKey(customerLogoutKey), content);

        return RestResult.success();
    }

    @Override
    public RestResult bigOrder(BigOrderWrapper wrapper) throws WxErrorException {
        String content = null;
        switch (wrapper.getCategory()) {
            case ride:
                content = bigOrderNotificationLogic.ride(wrapper.getRideId());
                break;
            case scanRide:
                content = bigOrderNotificationLogic.scanRide(wrapper.getRideId());
                break;
        }

        if (Objects.nonNull(content)) {
            WxCpGroupRobotService groupRobotService = wxCpService.getGroupRobotService();
            groupRobotService.sendMarkdown(getWebhookUrlByKey(orderAssistantKey), content);
        }
        return RestResult.success();
    }

    private String getWebhookUrlByKey(String key) {
        return "https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=" + key;
    }

    @Override
    public RestResult driverRegister(DriverRegisterNotificationWrapper wrapper) throws WxErrorException {
        DriverAuditInfo info = driverAuditInfoMapper.selectById(wrapper.getId());

        if (Objects.isNull(info)) {
            return RestResult.build(ResultEnum.NOT_FOUND);
        }

        String content = String.format("# 司机注册通知\n司机姓名: %s\n司机手机号: %s\n注册时间: %s", info.getName(), info.getMobileNumber(), DateUtil.format(info.getCreatedAt(), DatePattern.NORM_DATETIME_PATTERN));

        WxCpGroupRobotService groupRobotService = wxCpService.getGroupRobotService();

        groupRobotService.sendMarkdown(getWebhookUrlByKey(driverRegisterKey), content);
        return RestResult.success();
    }

    @Override
    public RestResult driverAuditCertificate(DriverCertificateExpirationWrapper wrapper) throws WxErrorException {
        int size = wrapper.getList().size();

        WxCpGroupRobotService groupRobotService = wxCpService.getGroupRobotService();

        if (size >= 20) {
            String content = String.format("# 证件过期预警\n共有%d名司机证件即将过期，请登录管理后台查看详情", size);

            groupRobotService.sendMarkdown(getWebhookUrlByKey(driverRegisterKey), content);
        } else {
            // 循环发
            for (DriverCertificateExpirationWrapper.DriverCertificateExpirationDto i : wrapper.getList()) {
                String content = String.format("# 证件过期预警\n司机姓名: %s\n司机手机号: %s\n证件类型: %s", i.getDriverName(), i.getMobileNumber(), i.getCertificateType().getDesc());
                groupRobotService.sendMarkdown(getWebhookUrlByKey(driverRegisterKey), content);
            }
        }

        return RestResult.success();
    }
}
